package com.proscenic.ops.mp.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.proscenic.ops.common.vo.ResultVO;
import com.proscenic.ops.mp.domain.MpMedia;
import com.proscenic.ops.mp.mapper.MpMediaMapper;
import com.proscenic.ops.mp.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @version 1.0
 * created by chenxin on 2021/11/1 17:22
 */
@Service
@Slf4j
public class MaterialServiceImpl implements MaterialService {
    @Resource
    private WxMpService wxMpService;
    @Resource
    private MpMediaMapper mpMediaMapper;

    @Override
    public ResultVO upload(HttpServletRequest request, String type, MultipartFile file) {
        try {
            WxMpMaterial material = new WxMpMaterial();
            File temp = FileUtil.writeFromStream(file.getInputStream(), new File("/temp/"+ IdUtil.simpleUUID()+"/"+file.getOriginalFilename()));
            material.setFile(temp);
            material.setName(temp.getName());
            WxMpMaterialUploadResult result = wxMpService.getMaterialService().materialFileUpload(type, material);

            MpMedia media = new MpMedia(type, result.getMediaId(), result.getUrl(), new Date());
            mpMediaMapper.insert(media);

        } catch (IOException | WxErrorException e){
            log.error("错误", e);
            return ResultVO.failed();
        }

        return ResultVO.success(null);
    }
}
